<template>
  <div class="modal modal-blur fade" id="modal-edit-plugin" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <form id="editPluginForm" class="needs-validation" novalidate>
          <div class="modal-header">
            <h5 class="modal-title">修改插件</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label required">插件名称</label>
              <input type="text" 
                     class="form-control" 
                     name="name" 
                     v-model="formData.name"
                     placeholder="请输入插件名称"
                     maxlength="50"
                     required>
              <div class="invalid-feedback">
                请输入插件名称
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">文件类型</label>
              <select class="form-select" 
                      id="fileType" 
                      name="fileType" 
                      v-model="formData.fileType"
                      required>
                <option value="">请选择文件类型</option>
                <option value="residentPlugin">residentPlugin</option>
                <option value="manager">manager</option>
                <option value="setup">setup</option>
              </select>
              <div class="invalid-feedback">
                请选择文件类型
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">版本号</label>
              <input type="text" 
                     class="form-control" 
                     name="version" 
                     v-model="formData.version"
                     placeholder="请输入版本号"
                     maxlength="30"
                     required>
              <div class="invalid-feedback">
                请输入版本号
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label">上传路径</label>
              <input type="text" 
                     class="form-control" 
                     name="path" 
                     v-model="formData.path"
                     placeholder="请输入上传路径"
                     maxlength="100">
            </div>
            <div class="mb-3">
              <label class="form-label">备注</label>
              <textarea class="form-control" 
                        rows="3" 
                        name="remark" 
                        v-model="formData.remark"
                        maxlength="200"
                        placeholder="请输入备注"></textarea>
              <div class="text-muted small">最多输入200个字符</div>
            </div>
            <div class="mb-3">
              <label class="form-label required">状态</label>
              <select class="form-select" 
                      id="enabled" 
                      name="enabled" 
                      v-model="formData.enabled"
                      required>
                <option value="1">启用</option>
                <option value="0">禁用</option>
              </select>
              <div class="invalid-feedback">
                请选择状态
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" 
                    class="btn btn-link link-secondary" 
                    data-bs-dismiss="modal">
              取消
            </button>
            <button type="submit" 
                    class="btn btn-primary ms-auto"
                    @click="submitEditPlugin">
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Modal } from 'bootstrap';

const props = defineProps({
  typeList: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['update-success']);

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const formData = reactive({
  id: '',
  name: '',
  fileType: '',
  version: '',
  path: '',
  remark: '',
  enabled: '1'
});

let editPluginModal;

onMounted(() => {
  editPluginModal = new Modal(document.getElementById('modal-edit-plugin'));
});

const openModal = (plugin) => {
  formData.id = plugin.id;
  formData.name = plugin.name;
  formData.fileType = plugin.fileType;
  formData.version = plugin.version;
  formData.path = plugin.path;
  formData.remark = plugin.remark;
  formData.enabled = plugin.status?.toString() || '1';
  editPluginModal.show();
};

const submitEditPlugin = async (event) => {
  event.preventDefault();
  event.stopPropagation();
  
  const form = document.getElementById('editPluginForm');
  form.classList.add('was-validated');
  
  if (!form.checkValidity()) {
    return;
  }

  try {
    const formDataToSend = new URLSearchParams();
    formDataToSend.append('id', formData.id);
    formDataToSend.append('name', formData.name);
    formDataToSend.append('fileType', formData.fileType);
    formDataToSend.append('version', formData.version);
    formDataToSend.append('path', formData.path);
    formDataToSend.append('remark', formData.remark);
    formDataToSend.append('enabled', formData.enabled);

    const response = await fetch(`${apiBaseUrl}/resident/plugin/update`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formDataToSend
    }  );
    
    const result = await response.json();
    if (result.success) {
      editPluginModal.hide();
      form.classList.remove('was-validated');
      emit('update-success');
    } else {
      alert('修改失败：' + (result.message || '未知错误'));
    }
  } catch (error) {
    console.error('Update error:', error);
    alert('修改失败，请稍后重试！');
  }
};

defineExpose({
  openModal
});
</script>

<style scoped>
.required:after {
  content: " *";
  color: red;
}

.form-control:invalid,
.form-select:invalid {
  border-color: #dc3545;
}

.form-control:invalid:focus,
.form-select:invalid:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
}

.was-validated .form-control:invalid,
.was-validated .form-select:invalid {
  border-color: #dc3545;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.was-validated .form-control:valid,
.was-validated .form-select:valid {
  border-color: #198754;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.invalid-feedback {
  display: none;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875em;
  color: #dc3545;
}

.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-select:invalid ~ .invalid-feedback {
  display: block;
}
</style> 